import { DatePicker, Form, GetRef, Input, InputRef, Select } from "antd";
import React, { useContext, useEffect, useRef, useState } from "react";
import dayjs from "dayjs";

//抽离可编辑的表格
type FormInstance<T> = GetRef<typeof Form<T>>;
const EditableContext = React.createContext<FormInstance<any> | null>(null);
interface Item {
  key: string;
  name: string;
  age: string;
  address: string;
}

interface EditableRowProps {
  index: number;
}

export const EditableRow: React.FC<EditableRowProps> = ({
  index,
  ...props
}) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

interface EditableCellProps {
  title: React.ReactNode;
  editable: boolean;
  dataIndex: keyof Item;
  record: Item;
  handleSave: (record: Item) => void;
  rules: any;
  type: string;
}

export const EditableCell: React.FC<
  React.PropsWithChildren<EditableCellProps>
> = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  rules,
  type,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef<InputRef>(null);
  const form = useContext(EditableContext)!;

  useEffect(() => {
    if (editing) {
      inputRef.current?.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    // console.log(dayjs(record[dataIndex]).format("YYYY-MM-DD"));
    form.setFieldsValue({
      [dataIndex]:
        type === "DatePicker" ? dayjs(record[dataIndex]) : record[dataIndex],
    });
  };

  const save = async () => {
    try {
      let values = await form.validateFields();

      // console.log(record[dataIndex], values[dataIndex].format("YYYY-MM-DD"));
      // console.log("新值", values[dataIndex]?.format?.("YYYY-MM-DD"));
      // if (record[dataIndex] === values[dataIndex]) return;
      if (Object.keys(values).includes("entryTime")) {
        values["entryTime"] = values["entryTime"]?.format?.("YYYY-MM-DD");
      }
      console.log(values);
      toggleEdit();
      handleSave({
        ...record,
        ...values,
      });
    } catch (errInfo) {
      console.log("Save failed:", errInfo);
      setEditing(!editing);
    }
  };

  let childNode = children;

  const EditCom: { [key: string]: React.ReactNode } = {
    Input: <Input ref={inputRef} onPressEnter={save} onBlur={save} />,
    Select: (
      <Select onBlur={save}>
        <Select.Option value="男">男</Select.Option>
        <Select.Option value="女">女</Select.Option>
      </Select>
    ),
    DatePicker: <DatePicker onChange={save} />,
  };

  if (editable) {
    childNode = editing ? (
      <Form.Item style={{ margin: 0 }} name={dataIndex} rules={rules}>
        {EditCom[type]}
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{ paddingInlineEnd: 0 }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};
